/*
 * Copyright (C) 2008-2010 Oliver Horn.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.funcj.tuples;

import java.io.Serializable;
import java.util.Arrays;

import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;

import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Supplier;
import com.googlecode.funcj.Transformable;

/**
 * An immutable tuple with a single element.
 *
 * @see Tuple
 *
 * @param <A> the type of the single element
 *
 * @author Oliver Horn
 */
@Immutable
public final class Single<A> implements Tuple, Supplier<A>, Transformable<A>, Serializable {

	private static final long serialVersionUID = 8259536860189420877L;

	private final A first;

	public Single(@Nullable A first) {
		this.first = first;
	}

	/**
	 * Returns the first (and only) element of this tuple.
	 * @return the single element
	 */
	public A first() {
		return first;
	}

	/**
	 * Returns the single element of this tuple.
	 * @return the single element
	 */
	public A get() {
		return first;
	}

	/**
	 * {@inheritDoc}
	 */
	public <V> Single<V> transform(Function<? super A, V> function) {
		return new Single<V>(function.apply(first));
	}

	/**
	 * {@inheritDoc}
	 * @return always {@code 1}
	 */
	public int arity() {
		return 1;
	}

	/**
	 * {@inheritDoc}
	 */
	public Object[] toArray() {
		return new Object[] { first };
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int hashCode() {
		return 31 + (first != null ? first.hashCode() : 0);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}
		if (obj instanceof Single) {
			Single<?> other = (Single<?>) obj;
			return Objects.equal(first, other.first);
		}
		if (obj instanceof Tuple) {
			Tuple other = (Tuple) obj;
			return (other.arity() == 1) && Arrays.equals(toArray(), other.toArray());
		}
		return false;
	}

	@Override
	public String toString() {
		return "(" + first + ",)";
	}
}
